package com.nbhx.oa;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import util.Constant;
import util.MovieFile;
import util.QADTimer;
import util.SQL;
import util.WatchDir.FileActionCallback;
import util.WatchDir.WatchDir;

public class QADByQDoc {
	// 移动文件对象
	static MovieFile movieFile = new MovieFile();
	SQL sql = new SQL();

	/**
	 * 读取xml文件内容
	 * 
	 * @throws IOException
	 * @throws SAXException
	 * @throws ParserConfigurationException
	 * @throws DocumentException
	 */

	private static String getXml(String pathString) throws IOException {
		SAXReader reader = new SAXReader();
		// 设置xml的字符编码为CB936
		reader.setEncoding(Constant.CB936ENCONDING);
		org.dom4j.Document document;
		try {
			document = reader.read(new File(pathString));
			String xmlString = document.asXML();
			return xmlString;
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			File file = new File(pathString);
			movieFile.movieXml(file);
			if (file.exists()) {
				file.delete();
			}
			e.printStackTrace();
		}
		return pathString;

	}

	/**
	 * 发送soap请求到服务器，并接受返回数据
	 * 
	 * @param codeFldname
	 *            ,codeValue,codeCmmt,codeGroup
	 * @return
	 */
	private InputStream getSoapInputStream(String xmlString) {
		try {
			String soap = xmlString;
			if (soap == null)
				return null;
			URL url = new URL(Constant.QDOCPATH);
			URLConnection conn = url.openConnection();
			conn.setUseCaches(false);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
			conn.setRequestProperty("Content-Length",
					Integer.toString(soap.length()));
			conn.setRequestProperty("SOAPAction", Constant.QDOCPATH_DEMO);
			OutputStream os = conn.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
			osw.write(soap);
			osw.flush();
			osw.close();
			InputStream is = conn.getInputStream();
			return is;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("连接到Qxtend服务出现问题，请检查QAD的相关设置!");
			return null;
		}
	}

	/**
	 * 请求提交
	 */
	public void postPRtoQAD(String xmlString, File file) {
		if(getSoapInputStream(xmlString)!=null){
		StringBuffer sb = new StringBuffer();
		InputStream is = null;
		try {
			is = getSoapInputStream(xmlString);
			outRuls(is, file);
		} catch (Exception e) {
			sb.append(e.getMessage());
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		}
	}

	/**
	 * 返回结果集处理
	 * 
	 * @param is
	 * @throws Exception
	 */
	public void outRuls(InputStream is, File file) throws Exception {
		boolean tag = false;
		Document document = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		DocumentBuilder db = dbf.newDocumentBuilder();
		document = db.parse(is);
		NodeList nlre = document.getElementsByTagName("ns1:result");
		NodeList nltt = document.getElementsByTagName("ns1:ttOutput");
		NodeList err_msg = document.getElementsByTagName("ns3:temp_err_msg");
		String resultString = "结果状态：";
		String dateString = "数据集：";
		String errorDateString = "错误消息：";

		if (nlre != null && nlre.getLength() > 0) {
			resultString = resultString + "," + nlre.item(0).getNodeValue();
			System.out.println("result:=>" + nlre.item(0).getNodeValue()); // 返回结果状态
		}

		for (int i = 0; nltt != null && i < nltt.getLength(); i++) {
			for (int j = 0; j < nltt.item(i).getChildNodes().getLength(); j++) {
				Node node = err_msg.item(i).getChildNodes().item(j);
				dateString = dateString + ";" + node.getLocalName() + "=>"
						+ node.getTextContent();
				System.out.println("Data[" + i + "][" + j + "]:=>"
						+ node.getLocalName() + "=>" + node.getTextContent()); // 返回数据集
			}
		}
		for (int i = 0; err_msg != null && i < err_msg.getLength(); i++) {
			for (int j = 0; j < err_msg.item(i).getChildNodes().getLength(); j++) {
				Node node = err_msg.item(i).getChildNodes().item(j);
				String reString = "Data[" + i + "][" + j + "]:=>"
						+ node.getLocalName() + "=>" + node.getTextContent();
				System.out.println(reString);
				int resulte = reString.indexOf("error");
				int resultE = reString.indexOf("ERROR");
				if (resulte != -1 || resultE != -1) {
					tag = true;
					// Connection connection = sql.connectSQL();
					// Statement stmt = connection.createStatement();
					// Date date = new Date();
					// String sqlString =
					// "INSERT INTO [swdhoa].[dbo].[formmain_4236] (ID,field0001,field0002,field0003) VALUES ('"
					// + date.getTime()
					// + "','"
					// + node.getLocalName()
					// + "=>" + reString + "','创建采购订单失败')";
					// System.out.println("SQL语句打印：" + sqlString);
					// boolean re = stmt.execute(sqlString);
					// System.out.println("执行数据库反馈" + re);
					// System.out.println("执行数据库反馈：成功");
					// System.out.println("执行数据库反馈：失败");
					// if (stmt != null) {
					// stmt.close();
					// }

				}
				// else {
				// sql.insertXmlSuccessLog(node);
				// }
				// errorDateString = errorDateString + ";" + node.getLocalName()
				// + "=>" + node.getTextContent();
				// System.out.println("Data[" + i + "][" + j + "]:=>"
				// + node.getLocalName() + "=>" + node.getTextContent()); //
				// 返回错误消息组

			}
		}

		// 判断是否写入过错误信息,如果写如果，就复制文件到另外一个目录
		if (tag) {
			movieFile.movieXml(file);
			file.delete();
		}
	}

	/*
	 * QAD供应商基础数据导入OA，每天两次
	 */
	public void supplierToOa() {
		SQL connectSQL = new SQL();
		// Connection connection = connectSQL.connectSQL();
	}

	public static void main(String[] args) throws Exception {
		System.out.println("请输入需要扫描的路径（D:/XML）");
		Scanner scan=new Scanner(System.in);
		String str=scan.next();
		final File file = new File(str);


		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					new WatchDir(file, true, new FileActionCallback() {
						public void create(File file) {
							System.out.println("创建文件\t"
									+ file.getAbsolutePath());
							if (file.isFile()) {
								try {
									System.out.println("等待5s后执行解析操作");
									for(int i=1;i<=5;i++){
										System.out.print(i);
										Thread.currentThread().sleep(500);
										System.out.print(".");
										Thread.currentThread().sleep(500);
									}
									System.out.println();
									System.out.println("正在根据XML文件("
											+ file.getName() + ")生成相关QAD数据");
									String pathNameString = file.getPath();// 取得文件目录
									String xmlString;
									xmlString = getXml(pathNameString);
									QADByQDoc tqq = new QADByQDoc();
									tqq.postPRtoQAD(xmlString, file);// 调用
									System.out.println(file.getName() + "处理完成");
									file.delete();
									System.out.println(file.getName() + "已删除");
								} catch (IOException | InterruptedException e) {
									e.printStackTrace();
								}// 取得xmlString
							}
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
		System.out.println("正在监视文件夹：" + file.getAbsolutePath() + "的变化");
	}
}